//
//  HMStatusVM.swift
//  HMWeibo12
//
//  Created by iOS on 16/9/20.
//  Copyright © 2016年 iOS. All rights reserved.
//

import UIKit

/// 负责处理单挑微博数据(新浪返回的微博数据很多是不能直接拿来使用)
class HMStatusVM: NSObject {

    /// 新浪返回的微博模型
    var status: HMStatus
    
    // MARK: - VM加工数据
    /// 会员等级图片
    var vipImage: UIImage?
    
    /// 认证类型图片
    var verifiedImage: UIImage?
    
    /// 原创微博的图片的URL
    var originalStatusPictureURLs: [URL]?
    
    /// 转发微博的图片的URL
    var retweetStatusPictureURLs: [URL]?
    
    /// 是否是转发微博
    var isRetweetedStatus = false
    
    /// 被转发微博文本
    var retweetStatusText: String?
    
    /// 转发的数量字符串
    var repostString: String?
    
    /// 评论的数量字符串
    var commentString: String?
    
    /// 赞的数量字符串
    var attitudeString: String?
    
    /// 处理后的来源
    var statusSource: String?
    
    /// 行高
    var rowHeight: CGFloat = 0
    
    /// 原创微博带图片的文本
    var originAttributeText: NSAttributedString?
    
    /// 被转发微博带图片的文本
    var retweetAttributeText: NSAttributedString?
    
    init(status: HMStatus) {
        self.status = status
        super.init()
        
        // 加工会员等级
        let mbrank = status.user?.mbrank ?? 0
        if mbrank > 0 && mbrank <= 6 {
            let imageName = "common_icon_membership_level\(mbrank)"
            vipImage = UIImage(named: imageName)
        } else {
            vipImage = nil
        }
        
        // 加工认证类型
        let verified_type = status.user?.verified_type ?? -1
        switch verified_type {
        case 0:
            verifiedImage = UIImage(named: "avatar_vip")
        case 2, 3, 5:
            verifiedImage = UIImage(named: "avatar_enterprise_vip")
        case 220:
            verifiedImage = UIImage(named: "avatar_grassroot")
        default:
            verifiedImage = nil
        }
        
        // 加工原创微博配图
        if let pic_urls = status.pic_urls {
            // 有图片
            originalStatusPictureURLs = [URL]()
            
            // 遍历微博返回的数组
            for dict in pic_urls {
                var urlString = dict["thumbnail_pic"] ?? ""
                
                // 替换成大一点的图片
                urlString = urlString.replacingOccurrences(of: "/thumbnail/", with: "/bmiddle/")
                
                let url = URL(string: urlString)!
                
                originalStatusPictureURLs?.append(url)
            }
        }
        
        // 判断是否是转发微博
        isRetweetedStatus = status.retweeted_status != nil
        
        
        // 被转发微博内容
        let retweetText = status.retweeted_status?.text ?? "被转发微博内容为空"
        let retweetName = status.retweeted_status?.user?.screen_name ?? "被转发微博用户名称"
        retweetStatusText = "@\(retweetName): \(retweetText)"
        
        // 原创微博带图片的文本
        originAttributeText = HMEmoticonManager.emoticonAttributeText(withString: status.text ?? "")
        
        // 被转发微博带图片的文本
        retweetAttributeText = HMEmoticonManager.emoticonAttributeText(withString: retweetStatusText ?? "")
        
        // 被转发微博的图片的URL
        if let pic_urls = status.retweeted_status?.pic_urls {
            retweetStatusPictureURLs = [URL]()
            
            for dict in pic_urls {
                var urlString = dict["thumbnail_pic"] ?? ""
                
                // 替换成大一点的图片
                urlString = urlString.replacingOccurrences(of: "/thumbnail/", with: "/bmiddle/")
                
                let url = URL(string: urlString)!
                
                retweetStatusPictureURLs?.append(url)
            }
        }
        
        // 处理数量
        let reposts_count = -100
//        let reposts_count = status.reposts_count
        let comments_count = status.comments_count
        let attitudes_count = status.attitudes_count
        
        repostString = countString(count: reposts_count, defaultString: "转发")
        commentString = countString(count: comments_count, defaultString: "评论")
        attitudeString = countString(count: attitudes_count, defaultString: "赞")
        
        splitSource()
        calcRowHeight()
    }
    
    /// 计算行高
    private func calcRowHeight() {
        // 顶部分割视图(10) + 头像顶部(8) + 头像高度(35) + 文字顶部(10) + 原创微博文字高度?
        // 原创微博特有: 原创微博配图的高度?
        // 转发微博特有: 被转发微博文本顶部(8) + 被转发微博文本高度? + 被转发微博配图高度?
        // 底部按钮顶部间距(8) + 底部按钮高度(40)
        rowHeight = 10 + HMStatusCellMargin + 35 + 10
        
        let size = CGSize(width: UIScreen.width - 2 * HMStatusCellMargin, height: CGFloat(MAXFLOAT))
        // 原创微博文字高度
        if let originAttributeText = originAttributeText {
//            let nsText = text as NSString
            // 根据给定的Size真正计算文字的宽高
            rowHeight += originAttributeText.boundingRect(with: size, options: .usesLineFragmentOrigin, context: nil).height
        }
        
        if isRetweetedStatus {
            // 转发微博
            rowHeight += HMStatusCellMargin
            
            // 注意: 被转发微博内容 @用户名称: 微博内容
            if let retweetAttributeText = retweetAttributeText {
                rowHeight += retweetAttributeText.boundingRect(with: size, options: .usesLineFragmentOrigin, context: nil).height
                
                rowHeight += calcSize(count: retweetStatusPictureURLs?.count ?? 0).height
            }
        } else {
            // 原创微博
            rowHeight += calcSize(count: originalStatusPictureURLs?.count ?? 0).height
        }
        
        rowHeight += HMStatusCellMargin
        rowHeight += 40
    }
    
    /// 计算配图大小
    ///
    /// - parameter count: 配图的数量
    ///
    /// - returns: 配图大小
    private func calcSize(count: Int) -> CGSize {
        if count == 0 {
            return CGSize()
        }
        
        // 列数
        var numberOfColumn = 3
        
        if count == 1 {
            numberOfColumn = 1
        } else if count == 2 || count == 4 {
            numberOfColumn = 2
        }
        
        // 计算行数? 已知总个数,已知列数,计算行数公式
        // 行数 = (总个数 + 列数 - 1) / 列数, 一定要记住,必须都是整数
        // 2 = (4 + 2 - 1) / 2
        // 2 = (6 + 3 - 1) / 3
        // 3 = (7 + 3 - 1) / 3
        let numberOfRow = (count + numberOfColumn - 1) / numberOfColumn
        
        // 计算总宽 = 列数 * 图片的宽度 + (列数 - 1) * 间距
        let width = CGFloat(numberOfColumn) * HMStatusPictureViewItemWH + (CGFloat(numberOfColumn) - 1) * HMStatusPictureViewItemMargin
        
        // 计算高度 = 行数 * 图片的高度 + (行数 - 1) * 间距
        // 内容从y = 8开始的
        let height = HMStatusCellMargin + CGFloat(numberOfRow) * HMStatusPictureViewItemWH + (CGFloat(numberOfRow) - 1) * HMStatusPictureViewItemMargin
        
        return CGSize(width: width, height: height)
    }
    
    //// 截取来源
    private func splitSource() {
        // 处理来源
        // <a href=\"http://app.weibo.com/t/feed/5B6hUc\" rel=\"nofollow\">iPhone 6s Plus</a>
        // ""
        // 截取来源
//        guard let sou = status.source else {
//            // status.source 没有值才进来
//        }
        
        if let source = status.source, source.characters.count > 0 {
            // status.source 有值才进来
            // 转成NSString,在截取字符串
            let nsSource = source as NSString
            
            let firstRange = nsSource.range(of: ">") // {50, 1}
//            print("source = \(source), \n firstRange.location = \(firstRange.location), firstRange.length = \(firstRange.length)")
            let lastRange = nsSource.range(of: "</") // {60, 2}
//            print("source = \(source), \n lastRange.location = \(lastRange.location), .lastRangelength = \(lastRange.length)")
            
            let subRange = NSRange(location: firstRange.location + 1, length: lastRange.location - firstRange.location - 1)
            statusSource = "来自 " + nsSource.substring(with: subRange)
//            print("statusSource: \(statusSource)")
            
        } else {
            // 没有来源
            statusSource = "来自 火星 "
        }
    }
    
    
    /// 计算 转发 评论 赞的数量转为字符串
    ///
    /// - parameter count:         数量
    /// - parameter defaultString: 默认的字符串
    ///
    /// - returns: 数量对应的字符串
    private func countString(count: Int, defaultString: String) -> String {
        if count <= 0 {
            return defaultString
        }
        
        if count >= 10000 {
            // 1.01 万
            // 10111 -> 1.0111 万 -> 1.01
            let newCount = Double(count) / 10000
            // ... 表示可变参数
            return String(format: "%.02f", newCount) + "万"
        } else {
            // 1 - 9999
            return "\(count)"
        }
    }
    
    override var description: String {
        get {
            return "\n\t HMStatusVM: status = \(status)"
        }
    }
}
